<?php


namespace app\controllers\api;

use app\daos\UserDao;
use app\models\Images;
use Slim;
use slimExt\base\Request;
use slimExt\base\Response;
use inhere\tools\files\Picture;

/**
 * Class Image
 * @package app\controllers
 */
class Image extends Base
{
    protected $paths = [
        'thumb' => '/public/images/thumbs',
        'water' => '/public/images/waters',
    ];

    /**
     * @method GET
     * @api /api/image/thumb
     * @args {
     *  id int
     *  path string 参数二选一
     *  // e.g. 50,100 --> width 50, height 100.
     *  // only limit width `100,0` `100`.
     *  // only limit height `0,100`.
     *  rule string 'w:h'
     * }
     *
     * e.g. /api/images/thumb?path=uploads/images/laminat.jpg&rule=100-80
     *
     * @param Request $req
     * @param Response $res
     * @return Response
     */
    public function thumbAction(Request $req, Response $res)
    {
        $id   = $req->getInt('id', 0);
        $path = $req->getTrimmed('path', '');
        $rule = $req->getTrimmed('rule', '100x80');

        if (!$path && $id) {
            $path = Images::findByPk($id, 'path')->path;
        }

        if (!$rule || !$path) {
            return $res->write('param error!');
        }

        $img = PROJECT_PATH . "/public/$path";

        if ( !is_file($img) ) {
            return $res->write('Image file dom\'t exists! file');
        }

        $info = pathinfo($img);
        $thumbFile = $info['dirname'] . '/thumbs/' . $info['filename']  . '_' . $rule . '.' . $info['extension'];

        // de($rule ,$img, $thumbFile,is_file($thumbFile) );

        if ( !is_file($thumbFile) ) {
            $rules = array_filter(explode('x', $rule), 'trim');
            if (isset($rules[1])) {
                list($w, $h) = $rules;
            } else {
                $w = $rules[0];
                $h = 0;
            }

            $pic = Picture::make([], [
                'path'   => dirname($img) . '/thumbs',
                'width'  => $w,
                'height' => $h,
                'suffix' => '_' .$rule,
            ])->thumbnail($img);

            if ($pic->hasError()) {
                return $res->write($pic->getError());
            }

            $thumbFile = $pic->working['out'];
        }

        Picture::show($thumbFile);

        return $res->withoutHeader('Content-type');
    }
}
